/*
* Copyright© 2018 Shanxi Lu'an Taihang Laihui Net Tech co.,LTD.
*/
package com.laihuichuxing.netty.common.core.session;

import com.google.protobuf.GeneratedMessage;
import com.laihuichuxing.netty.common.core.model.Response;

import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Description: 会话管理者
 *
 * @author YangGuang
 * @since: 1.0
 * Create Date Time: 2018/7/4 16:38
 * Update Date Time:
 * @see
 */
public class SessionManager {

    /**
     * 在线会话
     */
    private static final ConcurrentHashMap<String, Session> onlineSessions = new ConcurrentHashMap<>();

    /**
     * 加入
     * @param mobile
     * @param session
     * @return
     */
    public static boolean putSession(String mobile, Session session){
        if(!onlineSessions.containsKey(mobile)){
            boolean success = onlineSessions.putIfAbsent(mobile, session)== null? true : false;
            return success;
        }
        return false;
    }

    /**
     * 移除
     * @param mobile
     */
    public static Session removeSession(String mobile){
        return onlineSessions.remove(mobile);
    }

    /**
     * 发送消息[protoBuf协议]
     * @param <T>
     * @param mobile
     * @param message
     */
    public static <T extends GeneratedMessage> void sendMessage(String mobile, short module, short cmd, T message){
        Session session = onlineSessions.get(mobile);
        if (session != null && session.isConnected()) {
            Response response = new Response(module, cmd);
            if (message != null) {
                response.setData(message.toByteArray());
            }
            session.write(response);
        }
    }

    /**
     * 是否在线
     * @param mobile
     * @return
     */
    public static boolean isOnline(String mobile){
        return onlineSessions.containsKey(mobile);
    }

    /**
     * 获取在线
     * @return
     */
    public static Set<String> getOnline() {
        return Collections.unmodifiableSet(onlineSessions.keySet());
    }

    /**
     * 移除会话,关闭连接
     * @param mobile
     */
    public static void removeSessionCloseSocket(String mobile) {
        Session oldSession = SessionManager.removeSession(mobile);
        oldSession.removeAttachment();
        oldSession.close();
    }
}
